import {baseUrl} from './config.js'

// 请求错误消息提示
const showError=error=>{
	let errMsg=''
	switch(error.Ret){
		case 400:
			errMsg='请求参数错误';
			break;
		default:
			errMsg=error.ErrMsg;
			break;
	}
	uni.showToast({
		title:errMsg,
		icon:'none'
	})
}

// 请求数
let LOADINGCOUNT = 0;
const http=(url,params,method)=>{
	// 设置loading
	if (LOADINGCOUNT === 0) {
	  uni.showLoading({
	  	title:'加载中...'
	  })
	}
	LOADINGCOUNT++;
	
	let token=uni.getStorageSync('token')||''
	return new Promise((resolve,reject)=>{
		uni.request({
			url:baseUrl+url,
			data:params,
			method:method,
			header:{
				Authorization:token,
			},
			success(res) {
				if(res.data.Ret!==200){
					showError(res.data)
				}
				
				resolve(res.data)
			},
			fail(error) {
				console.log(error);
				uni.showToast({
					title:'服务器错误',
					icon:'none'
				})
			},
			complete() {
				// 关闭loading
				LOADINGCOUNT--;
				if (LOADINGCOUNT === 0) {
				  uni.hideLoading()
				}
			}
		})
	})
}

// get 请求
export const httpGet=(url,params)=>{
	return http(url,params,'GET')
}

// post 请求
export const httpPost=(url,params)=>{
	return http(url,params,'POST')
}